//
//  YLCProgramListView.m
//  LinYa
//
//  Created by 初程程 on 2018/1/27.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCProgramListView.h"
#import "YLCProgramListCell.h"
#import "YLCImageListViewController.h"
#import "YLCEasyVideoListViewController.h"
#define LIST_CELL   @"YLCProgramListCell"
@interface YLCProgramListView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,YLCProgramListCellDelegate>
@property (nonatomic, strong) UILongPressGestureRecognizer *longPress;
@end
@implementation YLCProgramListView
{
    UICollectionView *listTable;
    UIButton *imgBtn;
    UIButton *imageListBtn;
    UIButton *videoListBtn;
    NSArray *colorArr;
    NSMutableDictionary *cellDic;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.selectSignal = [RACSubject subject];
        self.reloadSignal = [RACSubject subject];
        self.listNewSignal = [RACSubject subject];
        cellDic = [NSMutableDictionary dictionary];
        [self createCustomView];
    }
    return self;
}
- (void)createCustomView{
    colorArr = @[@"#fbfced",@"#eefcf0",@"#ecf6fc"];
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    
    flow.minimumLineSpacing = 10;
    
    listTable = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flow];
    
    listTable.backgroundColor = YLC_COMMON_BACKCOLOR;
    
    [listTable registerClass:[YLCProgramListCell class] forCellWithReuseIdentifier:LIST_CELL];
    
    listTable.delegate =self;
    
    listTable.dataSource = self;
    
    [listTable setupNormalRefreshHeadAndFootWithTarget:self headAction:@selector(reloadData) footAction:@selector(didTriggerLoadNextPageData)];
    
    [listTable setupOnlyHeadRefrshWithTarget:self headAction:@selector(reloadData)];
    
    [self addSubview:listTable];
    
    _longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(lonePressMoving:)];
    [listTable addGestureRecognizer:_longPress];
    
    imgBtn = [YLCFactory createBtnWithImage:@""];
    
    imgBtn.backgroundColor = [UIColor redColor];
    
    [imgBtn addTarget:self action:@selector(gotoImageList) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:imgBtn];
    
    imageListBtn = [YLCFactory createBtnWithImage:@"easy_image_btn"];
    
    [imageListBtn addTarget:self action:@selector(gotoImageList) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:imageListBtn];
    
    videoListBtn = [YLCFactory createBtnWithImage:@"easy_video_btn"];
    
    videoListBtn.imageView.contentMode = UIViewContentModeScaleToFill;
    
    [videoListBtn addTarget:self action:@selector(gotoVideoList) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:videoListBtn];
}
- (void)beganRefresh{
    [listTable.mj_header beginRefreshing];
}
- (void)resetNoMore{
    [listTable.mj_footer endRefreshing];
}
- (void)loadedAllData{
    [listTable.mj_footer endRefreshingWithNoMoreData];
}
- (void)reloadData{
    [self.reloadSignal sendNext:@"0"];
}
- (void)didTriggerLoadNextPageData{
    
    NSInteger page = [_programList count]/[PAGE_LIMIT integerValue];

    [self.reloadSignal sendNext:[NSString stringWithFormat:@"%ld",page]];
}
- (void)gotoImageList{
    YLCImageListViewController *con = [[YLCImageListViewController alloc] init];
    
    con.classifyId = _classId;
    
    [(UINavigationController *)[YLCFactory currentNav] pushViewController:con animated:YES];
}
- (void)gotoVideoList{
    YLCEasyVideoListViewController *con = [[YLCEasyVideoListViewController alloc] init];
    
    con.classifyId = _classId;
    
    [(UINavigationController *)[YLCFactory currentNav] pushViewController:con animated:YES];
}
- (void)setProgramList:(NSArray *)programList{
    
    _programList = programList;
    
    if (JK_IS_ARRAY_NIL(_programList)) {
        YLCEmptyView *view = [[YLCEmptyView alloc] init];
        
        [listTable showEmptyViewWithEmptyView:view];
    }
    
    [listTable reloadData];
    
    [listTable.mj_header endRefreshing];
}
- (void)lonePressMoving:(UILongPressGestureRecognizer *)longPress{
    switch (_longPress.state) {
        case UIGestureRecognizerStateBegan: {
            {
                NSIndexPath *selectIndexPath = [listTable indexPathForItemAtPoint:[_longPress locationInView:listTable]];
                // 找到当前的cell
//                YLCProgramListCell *cell = (YLCProgramListCell *)[listTable cellForItemAtIndexPath:selectIndexPath];
                // 定义cell的时候btn是隐藏的, 在这里设置为NO
//                [cell.btnDelete setHidden:NO];
                [listTable beginInteractiveMovementForItemAtIndexPath:selectIndexPath];
            }
            break;
        }
        case UIGestureRecognizerStateChanged: {
            [listTable updateInteractiveMovementTargetPosition:[longPress locationInView:_longPress.view]];
            break;
        }
        case UIGestureRecognizerStateEnded: {
            [listTable endInteractiveMovement];
            break;
        }
        default: [listTable cancelInteractiveMovement];
            break;
    }
}
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(nonnull NSIndexPath *)sourceIndexPath toIndexPath:(nonnull NSIndexPath *)destinationIndexPath
{
    NSMutableArray *muta = [_programList mutableCopy];
    [muta exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
    _programList = [muta copy];
    [listTable reloadSections:[NSIndexSet indexSetWithIndex:0]];
    [self requestSort];
}
- (void)requestSort{
    NSMutableArray *array = [NSMutableArray array];
    for (YLCEasyProgramListModel *mod in _programList) {
        
        [array addObject:mod.product_id];
    }
    YLCAccountModel *model = [[YLCAccountManager shareManager] currentAccount];
    
    NSDictionary *parms = @{@"token":model.token,
                            @"userId":model.user_id,
                            @"classifyId":_classId,
                            @"orderId":array};
    [YLCNetWorking loadNetServiceWithLoadHidden:YES Param:parms method:@"POST" urlPath:@"app/sygt/setSeque" delegate:self response:^(id responseObject, NSError *error) {
        if (error||JK_IS_ARRAY_NIL(responseObject)) {
            return;
        }
    }];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _programList.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *identifier = [cellDic objectForKey:[NSString stringWithFormat:@"%@", indexPath]];
    if (identifier == nil) {
        identifier = [NSString stringWithFormat:@"YLCProgramListCell%@", [NSString stringWithFormat:@"%@", indexPath]];
        [cellDic setValue:identifier forKey:[NSString stringWithFormat:@"%@", indexPath]];
        [listTable registerClass:[YLCProgramListCell class]  forCellWithReuseIdentifier:identifier];
    }    
    
    YLCProgramListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    cell.delegate = self;
    
    cell.index = indexPath.row;
    
    cell.backgroundColor = [UIColor colorWithHexString:colorArr[indexPath.row%3]];
    
    if (indexPath.row<_programList.count) {
        cell.model = _programList[indexPath.row];
    }
    
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    YLCEasyProgramListModel *model = _programList[indexPath.row];
    
    CGSize size = [YLCFactory getStringSizeWithString:model.feature width:self.frameWidth-106 font:13.7];
    
    CGFloat tableHeight = 0;
    if (![model.options isKindOfClass:[NSNull class]]) {
        tableHeight = model.options.count*30;
    }
    return CGSizeMake(self.frameWidth, 150+size.height-20+tableHeight);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self.listNewSignal sendNext:_programList];
    [self.selectSignal sendNext:indexPath];
}
- (void)didTouchTableSelectAtIndex:(NSInteger)index{
    [self.selectSignal sendNext:[NSIndexPath indexPathForRow:index inSection:0]];
}
- (void)layoutSubviews{
    [super layoutSubviews];
    
    WS(weakSelf)
    
    [listTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
    
    [videoListBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakSelf.mas_bottom).offset(-50);
        make.right.equalTo(weakSelf.mas_right).offset(-20);
        make.width.height.equalTo(47);
    }];
    
    [imageListBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakSelf.mas_bottom).offset(-50);
        make.right.equalTo(videoListBtn.mas_left).offset(-20);
        make.width.height.equalTo(47);
    }];
//    WS(weakSelf)
//    [imgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(weakSelf.mas_right).offset(-60);
//        make.bottom.equalTo(weakSelf.mas_bottom).offset(-60);
//        make.width.height.equalTo(30);
//    }];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
